import 'dart:math';

import 'package:base_flutter/base_flutter.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/src/widgets/framework.dart';
import 'package:flutter/widgets.dart';
import 'package:gzx_dropdown_menu/gzx_dropdown_menu.dart';
import 'package:ls_work/viewmodel/choose_multi_elder_view_model.dart';
import 'package:ls_work/widgets/function_grid_widget.dart';

import '../a_yyt/models/floor_list_entity.dart';
import '../a_yyt/models/medical_elder_entity.dart';
import '../res/colors.dart';
import '../res/styles.dart';
import '../widgets/drop_item_widget.dart';

class ChooseMultiElderPage extends BaseStatefulMvvmWidget {
  List<MedicalElderInfo>? filterOld;

  ChooseMultiElderPage({this.filterOld});

  @override
  State<StatefulWidget> createState() => _ChooseMultiElderState();
}

class _ChooseMultiElderState extends BaseMvvmRefreshState<
    ChooseMultiElderViewModel, ChooseMultiElderPage> {
  GZXDropdownMenuController _dropdownMenuController =
      GZXDropdownMenuController();

  GlobalKey _stackKey = GlobalKey();

  @override
  Widget buildRootView(BuildContext context, Widget loadingContentWidget) {
    return Scaffold(
      backgroundColor: Colours.bg_color,
      appBar: AppBar(
        title: Text("选择长者"),
        actions: [
          CheckWithText(
            title: vm?.isAllChoose == true ? '取消全选' : '全选',
            onChanged: (value) {
              if (value) {
                viewModel.allClick();
              } else {
                viewModel.cancelCall();
              }
            },
            defaultSelected: vm?.isAllChoose ?? false,
            textStyle: TextStyle(fontSize: 14, color: Colors.black),
          ).addToContainer(margin: EdgeInsets.only(right: 16))
        ],
        elevation: 0,
      ),
      body: Stack(
        children: [
          Column(
            mainAxisAlignment: MainAxisAlignment.start,
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              GZXDropDownHeader(
                // 下拉的头部项，目前每一项，只能自定义显示的文字、图标、图标大小修改
                items: [
                  GZXDropDownHeaderItem(
                      viewModel.selectBuilding?.buildingNo ?? "全部"),
                  GZXDropDownHeaderItem(viewModel.selectFloor?.floorNo ?? "全部"),
                ],
                // GZXDropDownHeader对应第一父级Stack的key
                stackKey: _stackKey,
                // controller用于控制menu的显示或隐藏
                controller: _dropdownMenuController,
                height: 50,
                color: Colors.white,
                borderColor: Colors.white,
                dividerColor: Colors.white,

                style: TextStyle(color: Colors.black, fontSize: 16),
                dropDownStyle: TextStyle(
                  fontSize: 16,
                  color: Colours.app_main,
                ),
                iconSize: 22,
                iconColor: Colors.black,
              ).addToContainer(color: Colors.white),
              Container(
                color: Colours.bg_color,
                child: Row(
                  children: [
                    CommonInput(
                      hintText: "请输入房间号/姓名",
                      border: InputBorder.none,
                      isDense: true,
                      padding: EdgeInsets.zero,
                      textInputAction: TextInputAction.search,
                      onChanged: (str) {
                        viewModel.searchName = str;
                      },
                      needClear: false,
                      onSubmitted: (str) {
                        viewModel.requestRefresh();
                      },
                    ).setWeight(1),
                    Image.asset(
                      "assets/icon_search.png",
                      width: 16,
                      height: 16,
                    ).onTap(() {
                      viewModel.requestRefresh();
                    })
                  ],
                ).addToContainer(
                    margin: EdgeInsets.symmetric(horizontal: 16, vertical: 9),
                    decoration: BoxDecoration(
                        color: Colors.white, borderRadius: 30.borderRadius),
                    padding:
                        EdgeInsets.symmetric(horizontal: 10, vertical: 10)),
              ),
              loadingContentWidget.setWeight(1)
            ],
          ),

          // 下拉菜单
          GZXDropDownMenu(
            // controller用于控制menu的显示或隐藏
            controller: _dropdownMenuController,
            // 下拉菜单显示或隐藏动画时长
            animationMilliseconds: 300,
            dropdownMenuChanging: (isShow, index) {},
            dropdownMenuChanged: (isShow, index) {},
            menus: [
              if ((viewModel.buildingList ?? []).isNotEmpty)
                GZXDropdownMenuBuilder(
                  dropDownHeight: min(
                      40.0 * (viewModel.buildingList ?? []).length,
                      MediaQuery.of(context).size.height * 0.75),
                  dropDownWidget: buildConditionListWidget(
                      viewModel.buildingList ?? [], (data) {
                    _dropdownMenuController.hide();
                    setState(() {
                      viewModel.selectBuilding = data as FloorEntity?;
                      viewModel.setFloor();
                    });
                    viewModel.requestRefresh();
                  }),
                ),
              if ((viewModel.floorList ?? []).isNotEmpty)
                GZXDropdownMenuBuilder(
                  dropDownHeight: min(40.0 * (viewModel.floorList ?? []).length,
                      MediaQuery.of(context).size.height * 0.75),
                  dropDownWidget: buildConditionListWidget(
                      viewModel.floorList ?? [], (value) {
                    _dropdownMenuController.hide();
                    setState(() {
                      viewModel.selectFloor = value as FloorInfo?;
                    });
                    viewModel.requestRefresh();
                    print("floor====》");
                  }),
                ),
            ],
          ),
        ],
        key: _stackKey,
      ),
    );
  }

  @override
  Widget? buildLoadingContentView() {
    return Column(
      children: [
        super.buildLoadingContentView()!.setWeight(1),
        if(viewModel.chooseElders.isNotEmpty)
        Row(
          children: [
            SizedBox(width: 16,),
            TextButton(
                    onPressed: () {
                      viewModel.showSelectSheet();
                    },
                    child: CommonText('查看已选(${viewModel.chooseElders.length})',
                        textColor: Colors.white),
            style: ButtonStyle(
              backgroundColor: WidgetStateProperty.all(Colours.app_main,),
              shape: WidgetStateProperty.all(RoundedRectangleBorder(borderRadius: BorderRadius.horizontal(left: 22.radius)))
            ),)
                .setWeight(1),
            TextButton(
                    onPressed: () {
                      Go().pop(result: viewModel.chooseElders);
                    },
                    child: CommonText('保存', textColor: Colors.white),
            style: ButtonStyle(
              backgroundColor: WidgetStateProperty.all(Colors.blue),
                shape: WidgetStateProperty.all(RoundedRectangleBorder(borderRadius: BorderRadius.horizontal(right: 22.radius)))

            ),)
                .setWeight(1),

            SizedBox(width: 16,),
          ],
        ),
        SizedBox(height: 16,)
      ],
    );
  }

  @override
  Widget createScrollWidget() {
    var ori = MediaQuery.of(context).orientation;
    return SingleChildScrollView(
      child: FunctionGridColumn(
        // padding: EdgeInsets.symmetric(horizontal: 16),
        // gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
        count: ori == Orientation.portrait ? 3 : 6,
        mainSpace: 10.0,
        crossSpace: 10.0,
        // ),
        children: List.generate(viewModel.listItems.length, (index){
          var item = viewModel.listItems[index];
          return newOldContent(item).onTap(() {
            setState(() {
              if (viewModel.chooseElders.contains(item)) {
                viewModel.chooseElders.remove(item);
              } else {
                viewModel.chooseElders.add(item);
              }
            });
          });
        }),
      ),
      padding: EdgeInsets.symmetric(horizontal: 16),
    );
  }

  @override
  ChooseMultiElderViewModel createViewModel() {
    return ChooseMultiElderViewModel(context,filterOld: widget.filterOld);
  }

  @override
  bool get canPullUp => true;

  Widget newOldContent(MedicalElderInfo item) {
    return Stack(
      children: [
        Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          mainAxisSize: MainAxisSize.min,
          children: [
            Row(
              children: [
                Image.asset(
                  (item.sexName ?? "").contains('男')
                      ? 'assets/icon_old_male.png'
                      : 'assets/icon_old_female.png',
                  width: 24,
                  height: 23,
                ),
                SizedBox(width: 4,),
                Text(
                  item.name ?? "",
                  style: TextStyle(fontSize: 16),
                ),
              ],
            ),
            SizedBox(
              height: 5,
            ),
            Text(
              '${item.age ?? ""}岁',
              style: TextStyles.textGray14,
            ),
            SizedBox(
              height: 4,
            ),
            Text(
              '${item.floorNo}#${item.roomNo}',
              style: TextStyles.textGray14,
            ),
            SizedBox(
              height: 4,
            ),
            Text(
              item.nurseLevelName != null ? '${item.nurseLevelName}' : "",
              style: TextStyles.textGray14,
            ),
          ],
        ).addToContainer(padding: EdgeInsets.symmetric(horizontal: 4,vertical: 8),),
        // Icon(
        //   viewModel.chooseElders.contains(item)
        //       ? Icons.check_box
        //       : Icons.check_box_outline_blank,
        //   color:
        //       viewModel.chooseElders.contains(item) ? Colors.blue : Colors.grey,
        // ).setLocation(bottom: 5, right: 5),

       if(viewModel.chooseElders.contains(item))
       Transform.rotate(angle: pi/4,child:  Transform.rotate(angle: -pi/4,child: Icon(Icons.check,color: Colors.white,size: 18,),).addToContainer(
           color: Colors.amber,
           alignment: Alignment.centerLeft,
           width: 40,height: 40
       ),).setLocation(right: -20,bottom: -20)

      ],
    ).addToContainer(
        decoration:
            BoxDecoration(color: Colors.white, borderRadius: 4.borderRadius),);
  }
}
